<template>
  <div class="body page-miH page-bgBack">
    <div class="company">用工单位分组管理</div>
    <a-row class="mg_t20 mg_b20" type="flex" justify="space-between">
      <a-space :size="48">
        <a-input-search placeholder="搜索分组" style="width: 300px" allowClear @change="onChange" />
        <a-select v-model="isRecursion" style="width: 240px">
          <a-select-option :value="true">显示全部用工单位</a-select-option>
          <a-select-option :value="false">仅显示当前分组用工单位</a-select-option>
        </a-select>
      </a-space>
      <a-button icon="plus" type="primary" @click="addCompany">添加分组</a-button>
    </a-row>
    <div style="display: flex">
      <div style="width: 300px; flex-shrink: 0; overflow: auto">
        <a-tree
          v-if="selectedKeys.length > 0"
          :selectedKeys="selectedKeys"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          :treeData="groupTreeFilter"
          @expand="onExpand"
          @select="onGroupSelect"
        >
          <template slot="title" slot-scope="node">
            <div v-if="node.label.indexOf(searchValue) > -1" style="display: flex; align-items: center">
              <a-tooltip :title="node.label">
                <div class="title">
                  {{ node.label.substr(0, node.label.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ node.label.substr(node.label.indexOf(searchValue) + searchValue.length) }}
                </div>
              </a-tooltip>
              <a-icon v-if="node.editable" type="setting" @click="geDetail(node.value)" />
            </div>
            <div v-else style="display: flex; align-items: center">
              <a-tooltip :title="node.label">
                <div class="title">{{ node.label }}</div>
              </a-tooltip>
              <a-icon v-if="node.editable" type="setting" @click="geDetail(node.value)" />
            </div>
          </template>
        </a-tree>
      </div>
      <div class="ml24 pl24" style="flex: 1; border-left: 1px solid #e8e8e8">
        <a-table
          :pagination="pagination"
          :dataSource="dataSource"
          :loading="tableLoading"
          :columns="columns"
          :rowKey="(record) => record.id || 'site'"
          childrenColumnName="childList"
          @change="handleTableChange"
        >
          <template slot="action" slot-scope="text, record">
            <a-space>
              <a @click="management(record)">设置</a>
              <a @click="geEditor(record)">详情</a>
            </a-space>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { companyListByGroupIdReq } from "./api";
const columns = [
  {
    title: "用工单位名称",
    dataIndex: "name"
  },
  {
    title: "联系人",
    dataIndex: "legalPerson"
  },
  {
    title: "联系电话",
    dataIndex: "telephone"
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 100,
    scopedSlots: { customRender: "action" }
  }
];
export default {
  name: "CompanyManagement",

  data() {
    return {
      isRecursion: true,
      groupTreeFilter: [],
      selectedKeys: [],
      expandedKeys: [],
      searchValue: "",
      autoExpandParent: true,
      columns,
      dataSource: [],
      source: [],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "small",
        current: 1,
        showTotal: (total) => `共 ${total} 条`
      },
      tableLoading: false,
      currentGroup: null
    };
  },
  computed: {
    ...mapState(["hr", "site"]),
    groupTreeWithCompany() {
      return this.site.groupTreeWithCompany;
    },
    groupTreeFormatted() {
      return formatTree(this.groupTreeWithCompany);
    },
    groupList() {
      return generateList(this.groupTreeFormatted);
    }
  },
  watch: {
    groupTreeFormatted() {
      this.currentGroup = this.groupTreeFormatted[0]["value"];
      this.groupTreeFilter = this.groupTreeFormatted;
      this.expandedKeys = [this.groupTreeFormatted[0]["value"]];
    },
    currentGroup: {
      handler(newVal) {
        if (newVal) {
          this.pagination.current = 1;
          this.loadCompanyList();
          this.selectedKeys = [newVal];
        } else {
          this.dataSource = [];
          this.selectedKeys = [];
          this.pagination.total = 0;
        }
      }
    },
    isRecursion: {
      handler() {
        this.pagination.current = 1;
        this.loadCompanyList();
      }
    }
  },
  async created() {
    await this.$store.dispatch("site/loadGroupTreeAct");
    await this.$store.dispatch("site/loadGroupTreeWithCompanyAct");
  },
  methods: {
    ...mapMutations({ manageList: "admin/manageList" }),
    management(record) {
      this.$router.push({
        path: "/admin/switch",
        query: { id: record.id }
      });
    },
    geEditor(record) {
      this.$router.push({
        path: "/admin/add_employment_unit",
        query: { id: record.id }
      });
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadCompanyList();
    },
    loadCompanyList() {
      const params = {
        pageNo: this.pagination.current,
        pageSize: 10,
        isRecursion: this.isRecursion
      };
      if (this.currentGroup) {
        params["groupId"] = this.currentGroup;
      }
      companyListByGroupIdReq(params)
        .then((res) => {
          this.dataSource = res.data.entities;
          this.pagination.total = res.data.entityCount;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onGroupSelect(selectedKeys) {
      if (selectedKeys.length > 0) {
        this.currentGroup = selectedKeys[0];
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChange(e) {
      const value = e.target.value;
      this.groupTreeFilter = treeFilter(this.groupTreeFormatted, value);
      if (this.groupTreeFilter.length > 0) {
        this.currentGroup = this.groupTreeFilter[0]["value"];
        const expandedKeys = this.groupList
          .map((item) => {
            if (item.label.indexOf(value) > -1) {
              return getParentKey(item.value, this.groupTreeFilter);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true
        });
      } else {
        Object.assign(this, {
          currentGroup: null,
          expandedKeys: [],
          searchValue: value,
          autoExpandParent: true
        });
      }
    },
    // 详情
    geDetail(id) {
      this.$router.push({
        path: "/admin/add_company_management",
        query: { id: id }
      });
    },
    // 添加子公司
    addCompany() {
      this.manageList(this.dataSource);
      this.$router.push({
        path: "/admin/add_company_management"
      });
    }
  }
};

function formatTree(list) {
  const res = [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    res.push({
      key: item.id,
      value: item.id,
      label: item.name,
      editable: item.edit === true,
      children: item.companyList ? formatTree(item.companyList) : []
    });
  }
  return res;
}

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children && node.children.length > 0) {
      if (node.children.some((item) => item.value === key)) {
        parentKey = node.value;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

function treeFilter(tree, searchValue) {
  if (!tree || tree.length === 0) {
    return tree;
  }
  const treeTemp = [];
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.label.indexOf(searchValue) > -1) {
      treeTemp.push({
        ...node,
        children: treeFilter(node.children, searchValue)
      });
    } else {
      const childrenTemp = treeFilter(node.children, searchValue);
      if (childrenTemp.length > 0) {
        treeTemp.push({
          ...node,
          children: childrenTemp
        });
      }
    }
  }
  return treeTemp;
}

function generateList(tree) {
  let lstTemp = [];
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    lstTemp.push({ value: node.value, label: node.label });
    if (node.children) {
      lstTemp = lstTemp.concat(generateList(node.children));
    }
  }
  return lstTemp;
}
</script>
<style lang="scss" scoped>
::v-deep .ant-tree {
  li {
    span.ant-tree-switcher {
      height: 32px;
      line-height: 32px;
    }
    .ant-tree-node-content-wrapper {
      height: 32px;
      line-height: 32px;
    }
  }
}
.title {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.body {
  padding: 25px;
  .company {
    color: #333333;
    font-size: 16px;
  }
}
</style>
